
package com.feib.ebilling.job.service;

import java.io.*;   
import java.net.*;   
import java.util.*;

import javax.annotation.Resource;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import org.apache.commons.net.telnet.TelnetClient;

/**
 * @title (#)FtpService.java<br>
 * @description <br>
 * @author Yaude Huang<br>
 * @version 1.0.0 2012/02/17
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/12/11 create by Yaude Huang<br>
 */
@Service("telnetService")
@Scope(value=BeanDefinition.SCOPE_PROTOTYPE)
public class TelnetService extends BaseService {
	
	 public boolean connect() {		  
		  try {  
			  Properties props = new Properties();
			  String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
			  path = path.substring(1, path.length()).trim();
			  props.load(new FileInputStream(path + "spring-config.properties"));
			  String url = props.getProperty("dataSource.url");
			  int pos1 = url.indexOf("//"); 
			  int pos2 = url.indexOf(":", pos1);
			  String sIP = url.substring(pos1 + 2, pos2);
			  pos1 = pos2;
			  pos2 = url.indexOf(";");
			  String sPort = url.substring(pos1 + 1, pos2);
	          return connect(sIP, sPort);
		  }catch (Exception ex){
	          logger.info(ex.toString(), ex);
	          return false;
	      }
	 }	 
	 
     public boolean connect(String sIP, String sPort) {
              
        boolean bRtn = false;
        try {  
	        TelnetClient tc = new TelnetClient(); 
	        tc.connect(sIP, Integer.parseInt(sPort));
	        InputStream in = tc.getInputStream();
	        DataInputStream dis = new DataInputStream(in); 
	        if(dis != null){   
	        	logger.info("Connected with ip:{} and port:{} ok", sIP, sPort);
	        	in.close();
	        	tc.disconnect();
	        	bRtn = true; 
            }else{ 
            	logger.info("Connected with ip:{} and port:{} invalid", sIP, sPort);
            }
        }catch (Exception ex){
            logger.info(ex.toString(), ex);
        }    
        if (bRtn == false){
        	try {  
	        	/* 休息2分鐘一下再試 */
	        	Thread.sleep(120000);
        	}catch (Exception ex){
                logger.info(ex.toString(), ex);
            }  
        }
        return bRtn;
    }       
}
